using System;
using System.Collections.Generic;
using System.Text;
using Koda.Search;
using EnvDTE80;
using Koda.VisualStudio;
using EnvDTE;
using System.IO;
using Koda.Utils;

namespace Koda.Search.Finders
{
    public class FileFinder : VsFinderBase
    {
        private DTE2 dte;

        public FileFinder(DTE2 dte)
        {
            if (dte == null)
                throw new ArgumentNullException("dte");
            
            this.dte = dte;
        }

        protected override List<VsItem> Refresh()
        {
            ProjectItem[] projectItems = VsUtilities.GetAllProjectItemsInSolution(this.dte);
            List<VsItem> items = new List<VsItem>();

            foreach (ProjectItem projectItem in projectItems)
            {
                for (int i = 0; i < projectItem.FileCount; i++)
                {
                    string filename = projectItem.get_FileNames((short)(i + 1));
                    if (filename != null)
                    {
                        FileInfo fileInfo = new FileInfo(filename);
                        if (fileInfo.Exists)
                        {
                            VsItem item = new VsItem((uint)i, fileInfo.Name, fileInfo.FullName, fileInfo.FullName, VsItemType.File);
                            items.Add(item);
                        }
                    }
                }
            }

            return items;
        }

        public override bool OpenItem(VsItem item)
        {
            Window window = this.dte.ItemOperations.OpenFile(item.FullName, EnvDTE.Constants.vsViewKindPrimary);
            if (window != null)
            {
                return true;
            }
            return false;
        }
    }
}
